var service = require('./service');
var Router = require('koa-router');
var router = module.exports = new Router();

router.redirect('/login', '/account/login');
router.redirect('/logout', '/account/logout');

// 登录页面
router.get('/account/login', function * (next) {
  var data = yield service.getCaptcha(this);
  this.body = this.render('templates/login.html', data, this.query);
});

// 登录
router.post('/account/login', function * (next) {
  var self = this;
  var form = this.request.body;
  yield service.login(this, form).then(function (data) {
    self.session.member = data.memberEntity;
    self.session.account = data.accountEntity;
    self.session.projects = data.projectList;
    self.session.projectIds = data.projectIdList;
    self.session.partners = data.partnerUserInfoList;
    self.session.token = data.userToken;
    // BOSS角色
    self.session.puser = self.session.partners.filter(function (item) {
      return item.partnerType === 'bs';
    })[0];

    // 商户角色  
    var vendorInfo = self.session.partners.filter(function (item) {
      return item.partnerType === 'sh';
    })[0] || {};
    
    self.session.vendorId = vendorInfo['partnerId'];

    self.redirect(self.query.next || '/home');
  }, function (data) {
    return service.getCaptcha(self).then(function (captcha) {
      self.body = self.render('templates/login.html', form, captcha, {
        error: data.message || '您的账户不存在或密码错误'
      });
    });
  });
});

// 登出操作
router.get('/account/logout', function * (next) {
  this.session = null;
  this.redirect('/account/login?next=' + encodeURIComponent(this.headers.referer || '/home'));
});

// 验证码
router.get('/account/ajax/captcha', function * (next) {
  var self = this;
  var form = this.request.body;
  yield service.getCaptcha(this).then(function (data) {
    self.body = self.render(200, data);
  }, function (data) {
    self.body = self.render(500, data);
  });
});